import { UserConfig, ConfigEnv, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import { resolve } from 'path'
// import { uniPostcssPlugin } from '@dcloudio/uni-cli-shared'
import postcssImport from 'postcss-import'
import tailwindcss from 'tailwindcss'
import rename from 'postcss-class-rename'
import byebye from 'css-byebye'
import autoprefixer from 'autoprefixer'
import { manifest } from './modifyManifest'
import { proxy } from './build/proxy'
const root: string = process.cwd()
// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const {
    VITE_APP_ID,
    VITE_PORT,
    VITE_PUBLIC_PATH,
    VITE_OUT_DIR,
    VITE_ASSET_DIR,
    VITE_BASEURL,
  }: any = loadEnv(mode, root)
  manifest(VITE_APP_ID)
  return {
    base: VITE_PUBLIC_PATH,
    plugins: [uni()],
    css: {
      postcss: {
        plugins: [
          postcssImport({
            resolve(id, basedir, importOptions) {
              return id
            },
          }),
          tailwindcss(),

          // 根据平台差异进行不同的样式处理
          ...(process.env.UNI_PLATFORM !== 'h5'
            ? [
                // 使用postcss-class-name 包将小程序不支持的类名转换为支持的类名
                rename({
                  '\\\\:': '-',
                  '\\\\.': '_',
                }),
                byebye({
                  rulesToRemove: [/\*/],
                  map: false,
                }),
              ]
            : []),
          /* ******* */

          // uniPostcssPlugin(),
          autoprefixer({
            remove: true,
          }),
        ],
      },
    },
    // 解析相关 【别名】
    resolve: {
      alias: [
        {
          find: '@', //字符串｜正则
          replacement: resolve(__dirname, 'src'),
        },
        {
          find: '@static', //字符串｜正则
          replacement: resolve(__dirname, 'src/static'),
        },
      ],
    },
    // 服务相关
    server: {
      https: false,
      port: VITE_PORT,
      proxy: proxy(VITE_BASEURL),
    },
    // .构建相关【打包相关】
    build: {
      outDir: VITE_OUT_DIR,
      assetsDir: VITE_ASSET_DIR,
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
    },
  }
}
